﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace Test14_02Client
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpClient tcpClient = new TcpClient();
            tcpClient.Connect("127.0.0.1", 888);
            if (tcpClient != null)
            {
                Console.WriteLine("连接服务器成功");
                NetworkStream networkStream = tcpClient.GetStream();
                BinaryReader reader = new BinaryReader(networkStream);
                BinaryWriter writer = new BinaryWriter(networkStream);
                string localip = "127.0.0.1";
                IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
                foreach(IPAddress ip in ips)
                {
                    if (!ip.IsIPv6SiteLocal)
                        localip = ip.ToString();
                }
                writer.Write(localip + " 你好服务器，我是客户端！");//服务器端以空格分割字符串 若前面没空格会收不到消息==
                while (true)
                {
                    try
                    {
                        string strReader = reader.ReadString();
                        Console.WriteLine("来自服务器的消息：" + strReader);
                        if (strReader != null)
                        {
                            Console.WriteLine("来自服务器的消息：" + strReader);
                        }
                    }
                    catch
                    {
                        Console.WriteLine("未接收到消息" );
                        break;
                    }
                }
            }
            Console.WriteLine("连接服务器失败！");
        }
    }
}
